package com.easybuy.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.easybuy.entity.User;
import com.easybuy.service.UserService;
import com.easybuy.service.impl.UserServiceImpl;
import com.easybuy.util.ReturnResult;

public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private UserService userService = new UserServiceImpl();
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 目的：一个Servlet可以处理多个请求
		String action = request.getParameter("action");
		
		if (action != null) {
			switch (action) {
			case "toRegister":
				//跳转到注册页面去
				request.getRequestDispatcher("pre/register.jsp").forward(request, response);
				break;
			case "doRegister":
				//执行注册操作

				doRegister( request, response);
				break;

			default:
				response.sendRedirect("404.jsp");
				break;
			}
		} else {
			response.sendRedirect("404.jsp");
		}
		
		
		
	}

	private void doRegister(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		//拿参数
		
		User user = new User();
		
		user.setLoginName(request.getParameter("loginName"));
        user.setUserName(request.getParameter("userName"));
        user.setSex(Integer.parseInt(request.getParameter("sex")));
        user.setPassword(request.getParameter("password"));
        user.setIdentityCode(request.getParameter("identityCode"));
        user.setEmail(request.getParameter("email"));
        user.setMobile(request.getParameter("mobile"));
        user.setType(0); // 0 为普通用户，1位管理员
        
		//调用service的方法
        boolean result = userService.register(user);
		
        ReturnResult returnResult = new ReturnResult();
		//注册成功 
        if (result) {
			//跳转到登录页面
        	// {"status":1,"message":"注册成功"}
        	// fastjson
        	// 将需要传送到页面的  数据  封装成一个 对象
        	returnResult.setStatus(1);
        	returnResult.setMessage("注册成功");
		} else {
			//or 注册失败
			returnResult.setStatus(0);
        	returnResult.setMessage("注册失败");
		}
        
        String strJson = JSON.toJSONString(returnResult);
        System.out.println(strJson);
        out.print(strJson);
        out.flush();
        out.close();
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
